package com.hm.system.web;

import java.util.regex.Pattern;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hm.common.common.CommonUtil;
import com.hm.common.exception.ServiceException;
import com.hm.system.auto.SystemProperties;
import com.hm.system.mongo.domain.def.SysFileDef;
import com.hm.system.share.service.mongo.system.SysFileInfoService;
import com.hm.system.util.SystemConfigDef.Api.Rest;
import com.hm.system.util.plugin.baidu.ue.def.UeActionDef;
import com.hm.system.util.plugin.baidu.ue.vo.ImageConfig;
import com.hm.system.util.plugin.baidu.ue.vo.UploadResult;
import com.hm.system.web.su.BaseController;

import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

/**
 * @author shishun.wang
 * @date 上午10:24:47 2016年8月17日
 * @version 1.0
 * @describe
 */
@ResponseBody
@RestController
@RequestMapping(value = Rest.Sys.Plugin.REST_PLUGIN_BAIDU_UE)
public class BaiDuUeController extends BaseController {

	public static final String swaggerTag = "百度ue插件";

	private static final Logger logger = LoggerFactory.getLogger(BaiDuUeController.class);

	private static final Pattern BAIDU_UE_CALLBACK_Partten = Pattern.compile("^[a-zA-Z_]+[\\w0-9_]*$");

	@Autowired
	private SystemProperties systemProperties;

	@Autowired
	private SysFileInfoService sysFileInfoService;

	@Autowired
	private ObjectMapper objectMapper;

	@SuppressWarnings("unused")
	@RequestMapping(method = RequestMethod.GET)
	@ApiOperation(value = "BaiduUE统一调用入口", httpMethod = "GET", notes = "BaiduUE统一调用入口", tags = swaggerTag)
	public ResponseEntity<Object> getInvoke(
			@ApiParam(required = true, name = "callback", value = "callback") @RequestParam(value = "callback", required = false) String callback,
			@ApiParam(required = true, name = "action", value = "操作") @RequestParam(value = "action", required = true) UeActionDef action)
					throws JsonProcessingException {
		logger.trace("UE invoke get request with action {} and callback {}", action, callback);

		Object result = null;
		switch (action) {
		case config:
			ImageConfig imageConfig = new ImageConfig();
			imageConfig.setImageUrl(Rest.Sys.Plugin.REST_PLUGIN_BAIDU_UE);
			result = imageConfig;
			break;
		default:
			logger.error("Un support ue action {}", action);
			return ResponseEntity.badRequest().body(null);
		}
		if (result == null) {
			return ResponseEntity.badRequest().body(null);
		}
		if (CommonUtil.isEmpty(callback)) {
			return ResponseEntity.ok(result);
		} else {
			if (!validCallbackName(callback)) {
				return ResponseEntity.badRequest().body("callback parameter " + callback + " not valid");
			}
			return ResponseEntity.ok(callback + "(" + objectMapper.writeValueAsString(result) + ");");
		}
	}

	@RequestMapping(method = RequestMethod.POST)
	@ApiOperation(value = "BaiduUE统一调用入口,上传图片、视频等", httpMethod = "POST", notes = "BaiduUE统一调用入口", tags = swaggerTag)
	public ResponseEntity<Object> postInvoke(
			@ApiParam(required = true, name = "callback", value = "callback") @RequestParam(value = "callback", required = false) String callback,
			@ApiParam(required = true, name = "action", value = "操作") @RequestParam(value = "action", required = true) UeActionDef action,
			@ApiParam(required = false, name = "file", value = "附件文件") @RequestPart(value = "file", required = true) MultipartFile uploadMultipartFile)
					throws JsonProcessingException {
		logger.debug("UE invoke post request with action {} and callback {}", action, callback);
		Object result = null;
		switch (action) {
		case upload_image:
			result = uploadImage(uploadMultipartFile);
			break;
		default:
			logger.error("Un support ue action {}", action);
			return ResponseEntity.badRequest().body(null);
		}
		if (result == null) {
			return ResponseEntity.badRequest().body(null);
		}
		if (CommonUtil.isEmpty(callback)) {
			return ResponseEntity.ok(result);
		} else {
			if (!validCallbackName(callback)) {
				return ResponseEntity.badRequest().body("callback parameter " + callback + " not valid");
			}
			return ResponseEntity.ok(callback + "(" + objectMapper.writeValueAsString(result) + ");");
		}
	}

	private UploadResult uploadImage(MultipartFile uploadMultipartFile) {
		UploadResult resultBean = new UploadResult();
		if (uploadMultipartFile.isEmpty()) {
			resultBean.setState("上传文件为空");
			return resultBean;
		}
		resultBean.setOriginal(uploadMultipartFile.getOriginalFilename());
		resultBean.setTitle(uploadMultipartFile.getOriginalFilename());
		try {
			String upload = sysFileInfoService.upload(uploadMultipartFile, SysFileDef.IMAGE);
			resultBean.setUrl(CommonUtil.isNotEmpty(upload)
					? (systemProperties.getBaiduUe().getImageUrl() + "/" + upload) : "未知");
			return resultBean;
		} catch (Exception e) {
			logger.error("Failed store upload file " + uploadMultipartFile.getOriginalFilename(), e);
			if (e instanceof ServiceException) {
				resultBean.setState(((ServiceException) e).getMessage());
			} else {
				resultBean.setState(e.getMessage());
			}
			return resultBean;
		}
	}

	private boolean validCallbackName(String name) {
		if (BAIDU_UE_CALLBACK_Partten.matcher(name).matches()) {
			return true;
		}
		return false;
	}

}
